import axios from 'axios'
import qs from 'qs'
import { ElMessage } from 'element-plus'
import router from '../router/index';
import { useUserStore } from '../stores/user';
import constant from '@/utils/constant'
import { cacheNoneTokenRequestList, refreshAccessToken } from '@/utils/refresh'


const service = axios.create({
  // '/api'
  baseURL: constant.apiUrl,
  timeout: 60000,
  headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})

// 请求拦截器
service.interceptors.request.use(
  (config: any) => {

    const userStore = useUserStore()
    const { isCacheGet = true } = config
    config.ba
    // 请求鉴权
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }

    // 请求中文数据
    config.headers['Accept-Language'] = 'zh-CN'

    // 追加时间戳，防止GET请求缓存
    if (config.method?.toUpperCase() === 'GET' && isCacheGet) {
      config.params = { ...config.params, t: new Date().getTime() }
    }

    // 将表单提交数据对象序列化成URL的形式
    if (Object.values(config.headers).includes('application/x-www-form-urlencoded')) {
      config.data = qs.stringify(config.data)
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const { data: res, config, request } = response
    const userStore = useUserStore()

    // 响应成功
    if (res.code === 200 || request.responseType === 'blob') {
      return res
    }

    // 没有权限，如：未登录、登录token过期等，需要刷新token，或直接跳转到登录页
    if (res.code === 401) {
      if (userStore.refreshToken) {
        return new Promise(resolve => {
          cacheNoneTokenRequestList(() => resolve(service(config)))
          refreshAccessToken()
        })
      } else {
        // 清除token，并跳转到登录页
        userStore.setToken('')
        router.replace('/login')
      }
    }

    // 错误提示
    if (config.showErrorAlert !== false) {
      ElMessage.closeAll()
      ElMessage.error(res.msg)
    }

    return Promise.reject(new Error(res.msg || '系统错误！'))
  },
  error => {
    ElMessage.closeAll()
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

// 导出 axios 实例
export default service
